<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="学生姓名" prop="name">
        <el-input
          v-input-restrict
          v-model="queryParams.name"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学号" prop="studentNum">
        <el-input
          v-input-restrict
          v-model="queryParams.studentNum"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        v-if="!$route.query.classId && $store.getters.roles[0]!='finance' && $store.getters.roles[0]!='branchAdmin'"
        :label="`${$branchName ? $branchName : '分院'}`"
        prop="branchId"
      >
        <el-select
          filterable
          @change="branchChange($event, 'queryParams')"
          v-model="queryParams.branchId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in form_branchs"
            :key="index"
            :label="item.branchName"
            :value="parseInt(item.branchId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="!$route.query.classId"
        :label="`${$majorName ? $majorName : '专业'}`"
        prop="majorId"
      >
        <el-select
          filterable
          @change="majorChange($event, 'queryParams')"
          v-model="queryParams.majorId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in form_majors"
            :key="index"
            :label="item.majorName"
            :value="parseInt(item.majorId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="!$route.query.classId"
        :label="`${$gradeName ? $gradeName : '班级'}`"
        prop="classId"
      >
        <el-select
          filterable
          v-model="queryParams.classId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in form_classes"
            :key="index"
            :label="item.className"
            :value="parseInt(item.classId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button v-preventReClick-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          >修改</el-button-->
      <!--        >-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleSwitch('all')"
          >批量停用</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
          <el-button v-preventReClick
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:post:export']"
          >导出</el-button>
        </el-col> -->
      <el-col :span="1.5">
        <el-upload
          multiple
          :http-request="handleImport"
          :show-file-list="false"
          action="#"
          accept=".xls,.xlsx"
          ref="upload"
        >
          <el-button
            v-preventReClick
            type="warning"
            plain
            icon="el-icon-folder-add"
            size="mini"
            >导入</el-button
          >
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleTemplate"
          >下载模板</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div
      style="
        font-size: 14px;
        font-weight: 400;
        color: rgba(128, 128, 128, 1);
        margin: 13px 0 8px 0;
      "
      class="flex"
      v-if="$route.query.classId"
    >
      <div style="margin-left: 20px">
        {{ $branchName ? $branchName : "分院" }} : {{ $route.query.branchName }}
      </div>
      <div style="margin-left: 20px">
        {{ $majorName ? $majorName : "专业" }} : {{ $route.query.majorName }}
      </div>
      <div style="margin-left: 20px">
        {{ $gradeName ? $gradeName : "班级" }} : {{ $route.query.className }}
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学号" align="center" prop="studentNum" />

      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="分院" align="center" prop="branchName" />
      <el-table-column label="专业" align="center" prop="majorName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          {{ scope.row.sex == 0 ? "男" : "女" }}
        </template>
      </el-table-column>

      <el-table-column
        label="必修学分"
        align="center"
        prop="compulsoryCredit"
      />
      <el-table-column label="选修学分" align="center" prop="optionalCredit" />
      <el-table-column label="考证学分" align="center" prop="researchCredit" />
      <el-table-column
        label="工学学分"
        align="center"
        prop="engineeringCredit"
      />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            @change="handleSwitch(scope.row)"
            :active-value="0"
            :inactive-value="1"
            :value="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-button slot="reference" type="text" size="mini"
                >更多<i class="el-icon-arrow-down"></i
              ></el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                ><el-button
                  v-preventReClick
                  size="mini"
                  type="text"
                  icon="el-icon-refresh"
                  @click="handleReset(scope.row)"
                  >重置密码</el-button
                ></el-dropdown-item
              >
              <el-dropdown-item>
                <el-button
                  v-preventReClick
                  size="mini"
                  type="text"
                  style="color: #E95756"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                ></el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      :visible.sync="open"
      width="650px"
      append-to-body
    >
      <el-form @submit.native.prevent ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col v-if="$route.query.branchName" :span="8"
            ><el-form-item
              :label="`${$branchName ? $branchName : '分院'}名称`"
              prop=""
            >
              {{ $route.query.branchName }}
            </el-form-item></el-col
          >
          <el-col v-if="$route.query.majorName" :span="8"
            ><el-form-item
              :label="`${$majorName ? $majorName : '专业'}名称`"
              prop=""
            >
              {{ $route.query.majorName }}
            </el-form-item></el-col
          >
          <el-col v-if="$route.query.className" :span="8"
            ><el-form-item
              :label="`${$gradeName ? $gradeName : '班级'}名称`"
              prop=""
            >
              {{ $route.query.className }}
            </el-form-item></el-col
          >
        </el-row>
        <el-form-item label="照片" prop="photo">
          <div class="flex">
            <!-- 上传图片 -->
            <div v-if="form.photo" class="upload-head" @click="editCropper()">
              <img v-bind:src="form.photo" class="cover" />
            </div>
            <div v-else class="upload-head" @click="editCropper()">
              <div>
                <img src="@/assets/images/add.png" class="add" alt="" />
              </div>
              <div>上传图片</div>
            </div>

            <div class="uploadTip">
              建议图片比例5:7，支持jpg、png格式，图片小于5M
            </div>
          </div>

          <vuecut
            :h="280"
            :url="form.photo"
            @coverResult="coverResult"
            title="图片上传"
            :open.sync="vuecutshow"
          ></vuecut>
        </el-form-item>
        <el-form-item label="学生姓名" prop="name">
          <el-input
          v-input-restrict
            v-model="form.name"
            maxlength="10"
            show-word-limit
            placeholder="请输入学生姓名"
          />
        </el-form-item>
        <el-form-item label="学号" prop="studentNum">
          <el-input
          v-input-restrict
            maxlength="20"
            show-word-limit
            v-model="form.studentNum"
            :disabled="title == '修改学生'"
            placeholder="请输入学号"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input
          v-input-restrict v-model="form.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input
          v-input-restrict v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item
          v-if="!$route.query.classId && $store.getters.roles[0]!='finance' && $store.getters.roles[0]!='branchAdmin'"
          :label="`${$branchName ? $branchName : '分院'}`"
          prop="branchId"
        >
          <el-select v-model="form.branchId" @change="branchChange(form.branchId)" placeholder="请选择" clearable>
            <el-option
              v-for="(item, index) in form_branchs"
              :key="index"
              :label="item.branchName"
              :value="item.branchId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="!$route.query.classId"
          :label="`${$majorName ? $majorName : '专业'}`"
          prop="majorId"
        >
          <el-select v-model="form.majorId" @change="majorChange(form.majorId)" placeholder="请选择" clearable>
            <el-option
              v-for="(item, index) in form_majors"
              :key="index"
              :label="item.majorName"
              :value="item.majorId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="!$route.query.classId"
          :label="`${$gradeName ? $gradeName : '班级'}`"
          prop="classId"
        >
          <el-select v-model="form.classId" placeholder="请选择" clearable>
            <el-option
              v-for="(item, index) in form_classes"
              :key="index"
              :label="item.className"
              :value="item.classId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancel">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitForm"
          >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPost_branch,
  listPost_major,
  listPost_class,
} from "@/api/schoolOrganization/organization";
import {
  addPost_changeStatus,
  addPost_resetPwd,
  listPost_student,
  getPost_student,
  delPost_student,
  addPost_student,
  updatePost_student,
  checkStudentNum,
  import_student,
} from "@/api/schoolOrganization/student";
import { checkidCardnot, checkPhonenot } from "@/utils/validate";
export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      vuecutshow: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        branchId: undefined,
        majorId: undefined,
        classId: undefined,
        studentNum: undefined,
      },
      // 表单参数
      form: {
        branchId: undefined,
        majorId: undefined,
        classId: undefined,
        photo: undefined,
        studentNum: undefined,
        name: undefined,
        sex: undefined,
        phoneNumber: undefined,
        idCard: undefined,
      },
      // 表单校验
      rules: {
        branchId: [
          {
            required: true,
            message: `${this.$branchName ? this.$branchName : "分院"}不能为空`,
            trigger: "blur",
          },
        ],
        majorId: [
          {
            required: true,
            message: `${this.$majorName ? this.$majorName : "专业"}不能为空`,
            trigger: "blur",
          },
        ],
        classId: [
          {
            required: true,
            message: `${this.$gradeName ? this.$gradeName : "班级"}不能为空`,
            trigger: "blur",
          },
        ],
        photo: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        studentNum: [
          { required: true, message: "学号不能为空", trigger: "blur" },
          // { min: 7, message: "学号长度不能小于7位" },
        ],
        sex: [{ required: true, message: "性别不能为空", trigger: "blur" }],
        idCard: [
          { required: false, validator: checkidCardnot, trigger: "blur" },
        ],
        phoneNumber: [
          { required: false, validator: checkPhonenot, trigger: "blur" },
        ],
      },
      //   分院列表
      queryParams_branchs: [],
      queryParams_majors: [],
      queryParams_classes: [],
      form_branchs: [],
      form_majors: [],
      form_classes: [],
    };
  },
  watch: {
    form_classes: {
      immediate: true,
      handler(val) {
        if (val.length == 1) {
          this.form.classId = val[0].classId;
        }
      },
    },
    form_majors: {
      immediate: true,
      handler(val) {
        if (val.length == 1) {
          this.form.majorId = val[0].majorId;
        }
      },
    },
    "form.branchId": {
      deep: true,
      async handler(val) {
        if (!val) {
          this.form.majorId = undefined;
          this.form.classId = undefined;
          this["form_classes"] = [];
          this["form_majors"] = [];
        } else {
          let response = await listPost_major({
            pageNum: 1,
            pageSize: 999,
            branchId: val,
          });
          this["form_majors"] = response.rows;
        }
      },
    },
    "form.majorId": {
      deep: true,
      async handler(val) {
        if (!val) {
          this.form.classId = undefined;
          this["form_classes"] = []
        } else {
          let response = await listPost_class({
            pageNum: 1,
            pageSize: 999,
            majorId: val,
          });
          this["form_classes"] = response.rows;
        }
      },
    },
  },
  created() {
    // 如果是班级管理跳转 检索自动带上classid
    this.queryParams.classId = this.$route.query.classId;
    if ( this.$store.getters.roles[0] != "finance" && this.$store.getters.roles[0] != "branchAdmin" ) {
      this.getBranch();
    }else{
      this.queryParams.branchId = this.$store.getters.branchId
      this.form.branchId = this.$store.getters.branchId
    }
    this.getList();
  },
  methods: {
    handleTemplate() {
      window.location.href = "/static/stu.xlsx";
    },
    async handleImport(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      const loading = this.$loading({
        lock: true,
        text: "正在上传,请稍等…",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      import_student(formData)
        .then((response) => {
          loading.close();
          this.$modal.msgSuccess("导入成功");
          this.getList();
        })
        .catch((err) => {
          loading.close();
        });
    },
    handleDetail(row) {
      this.$router.push({
        path: "/schoolOrganization/studentDetail",
        query: {
          studentId: row.studentId,
        },
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const postId = row.studentId || this.ids;
      let response = await getPost_student(postId);
      //这里需要获取 专业以及班级列表
      let major = await listPost_major({
        pageNum: 1,
        pageSize: 999,
        branchId: response.data.branchId,
      });
      this.form_majors = major.rows;
      let classes = await listPost_class({
        pageNum: 1,
        pageSize: 999,
        majorId: response.data.majorId,
      });
      this.form_classes = classes.rows;
      this.open = true;
      this.title = "修改学生";
      this.form = response.data;
    },
    async branchChange(val) {
      this.form.majorId = undefined;
      this.form.classId = undefined;
      this.queryParams.majorId = undefined;
      this.queryParams.classId = undefined;
      this["form_classes"] = [];
      this["form_majors"] = [];
      if (val){
        let response = await listPost_major({
          pageNum: 1,
          pageSize: 999,
          branchId: val,
        });
        this["form_majors"] = response.rows;
      }
    },
    async majorChange(val) {
      this.form.classId = undefined;
      this.queryParams.classId = undefined;
      this["form_classes"] = [];
      if (val){
        let response = await listPost_class({
          pageNum: 1,
          pageSize: 999,
          majorId: val,
        });
        this["form_classes"] = response.rows;
      }
    },
    getBranch() {
      listPost_branch({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
      }).then((response) => {
        this.queryParams_branchs = response.rows;
        this.form_branchs = response.rows;
      });
    },
    /** 组件返回图片 */
    coverResult(e) {
      this.form.photo = e;
    },
    editCropper() {
      this.vuecutshow = true;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      // 如果url带班级id
      listPost_student(this.queryParams).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if ( this.$store.getters.roles[0] != "finance" && this.$store.getters.roles[0] != "branchAdmin" ) {
        this.form = {
          classId: undefined,
          branchId: undefined,
          majorId: undefined,
          photo: undefined,
          studentNum: undefined,
          name: undefined,
          sex: undefined,
          phoneNumber: undefined,
          idCard: undefined,
        };
      }else {
        this.form = {
          classId: undefined,
          majorId: undefined,
          photo: undefined,
          studentNum: undefined,
          name: undefined,
          sex: undefined,
          phoneNumber: undefined,
          idCard: undefined,
        };
        this.form.branchId = this.$store.getters.branchId
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.classId = this.$route.query.classId
        ? this.$route.query.classId
        : this.$route.query.classId;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.studentId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      let res = await checkStudentNum();
      if (res.data) {
        this.reset();
        if ( this.$store.getters.roles[0] != "finance" && this.$store.getters.roles[0] != "branchAdmin" ) {
          if (this.form_branchs.length == 1) {
            this.form.branchId = this.form_branchs[0].branchId;
          }
        }else {
          this.form.branchId = this.$store.getters.branchId
        }
        this.open = true;
        this.title = "添加学生";
      } else {
        this.$modal.msgWarning("当前已达到学生数量限制");
      }
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.schoolId = this.$store.getters.schoolId;
          // 如果url带班级id
          this.form.classId = this.$route.query.classId
            ? this.$route.query.classId
            : this.form.classId;
          this.form.majorId = this.$route.query.majorId
            ? this.$route.query.majorId
            : this.form.majorId;
          this.form.branchId = this.$route.query.branchId
            ? this.$route.query.branchId
            : this.form.branchId;
          if (this.form.studentId != undefined) {
            updatePost_student(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost_student(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.studentId || this.ids;
      this.$modal
        .confirm("确定删除？")
        .then(function () {
          return delPost_student(postIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleReset(row) {
      const postIds = row.studentId;
      this.$modal
        .confirm("确定重置密码？")
        .then(function () {
          return addPost_resetPwd(postIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("重置密码成功");
        })
        .catch(() => {});
    },
    handleSwitch(row) {
      let newstatus;
      const postIds = row.studentId || this.ids;
      let can = false;
      if (row !== "all") {
        newstatus = row.status == 0 ? 1 : 0;
        this.changeStatus(postIds, newstatus, row);
      } else {
        newstatus = 1;
        this.$modal
          .confirm("确定批量停用？")
          .then(() => {
            this.changeStatus(postIds, newstatus, row);
          })
          .catch(() => {});
      }
    },
    changeStatus(postIds, newstatus, row) {
      let formData = new FormData();
      formData.append("studentIds", postIds);
      formData.append("status", newstatus);
      addPost_changeStatus(formData)
        .then((res) => {
          this.$modal.msgSuccess("修改状态成功");
          if (row == "all") {
            this.getList();
          } else {
            row.status = row.status == 0 ? 1 : 0;
          }
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep.uploadTip {
  height: 210px;
  line-height: 390px;
}

.upload-head {
  width: 152px;
  height: 212px;

  .add {
    width: 29px;
    height: 29px;
    margin: 70px 0 0 0px;
  }

  .cover {
    width: 150px;
    height: 210px;
    border-radius: 4px;
  }
}

.upload-head:hover:after {
  line-height: 210px;
}
</style>
